package com.cls.business.controller;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.cls.business.entity.*;
import com.cls.business.service.*;
import com.cls.business.vo.DeclareTopicVO;
import com.cls.business.vo.DeclareVo;
import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.enums.DictEnum;
import com.cls.common.exception.MyException;
import com.cls.common.utils.MyUtil;
import com.cls.common.entity.MyConstant;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.QueryRequest;
import com.cls.common.entity.ResponseVO;
import com.cls.system.entity.SysDict;
import com.cls.system.entity.SysFile;
import com.cls.system.entity.User;
import com.cls.system.service.ISysDictService;
import com.cls.system.service.ISysFileService;
import com.github.pagehelper.PageInfo;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 委托课题信息附表 Controller
 *
 * @author slx
 * @date 2020-12-02 14:25:22
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class DeclareEntrustController extends BaseController {
    private final IDeclareTopicService declareTopicService;
    private final IDeclareEntrustService declareEntrustService;
    private final ISysDictService sysDictService;
    private final IApplicantInfoService applicantInfoService;
    private final IMemberInfoRecordService memberInfoRecordService;
    private final IDelayApplyService delayApplyService;
    private final ISysFileService sysFileService;
    private final ITopicService topicService;

    /**
    * 委托课题信息附表列表页面
    **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareTopicEntrust")
    public String declareEntrustIndex(Model model){
        List<SysDict> subjectTypes = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectTypes",subjectTypes);
        return MyUtil.view("business/entrust/entrust");
    }

    /**
    * 委托课题信息附表详情页面
    * @return
    */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareEntrust/declareEntrustDetail/{declareEntrustId}")
    public String declareEntrustDetail(@PathVariable Long declareEntrustId, Model model){
        DeclareEntrust declareEntrust = declareEntrustService.getById(declareEntrustId);
        model.addAttribute("declareEntrust",declareEntrust);
        return MyUtil.view("business/declareEntrust/declareEntrustDetail");
    }

    @GetMapping("declareEntrust")
    @ResponseBody
    @RequiresPermissions("declareEntrust:list")
    public ResponseVO getAllDeclareEntrusts(DeclareEntrust declareEntrust) {
        return ResponseVO.success(declareEntrustService.findDeclareEntrusts(declareEntrust));
    }

    @GetMapping("declareEntrust/list")
    @ResponseBody
    @RequiresPermissions("declareEntrust:list")
    public ResponseVO declareEntrustList(QueryRequest request, DeclareVo declareVo) {
        declareVo.setTopicClassifyCode(DictEnum.ENTRUST.getCode());
        declareVo.setExamine(DictEnum.INFO_NO.getCode());
       // PageInfo<DeclareVo> pageInfo =  this.declareEntrustService.findDeclareEntrustPage(request, declareVo);
        PageInfo<DeclareVo> pageInfo =  this.declareEntrustService.findDeclareEntrustPageOrder(request, declareVo);
        return ResponseVO.success(pageInfo);
    }

    @GetMapping("declareEntrust/getList")
    @ResponseBody
    public ResponseVO declareEntrustApiList(QueryRequest request, DeclareVo declareVo) {
        declareVo.setTopicClassifyCode(DictEnum.ENTRUST.getCode());
        User user = getCurrentUser();
        //跟根据用户查询

        ApplicantInfo byUserId = applicantInfoService.findByUserId(user.getUserId());
        declareVo.setApplicantId(byUserId.getApplicantId());
        PageInfo<DeclareVo> pageInfo =  this.declareEntrustService.findDeclareEntrustPage(request, declareVo);
        return ResponseVO.success(pageInfo);
    }


    @ControllerEndpoint(operation = "删除单个", exceptionMessage = "删除失败")
    @PostMapping("declareEntrust/delete/{declareId}")
    @ResponseBody
    public ResponseVO deleteDeclareEntrust(@PathVariable Long declareId) {
        this.declareTopicService.removeEntrustById(declareId);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "委托课题信息", exceptionMessage = "新增委托课题失败")
    @PostMapping("entrustAdd")
    @ResponseBody
    public ResponseVO addEntrust(@RequestBody DeclareTopicVO declareTopicVO) {
        //新增
        Topic byId = topicService.getById(declareTopicVO.getTopicId());
        declareTopicVO.setTopicCode(byId.getTopicCode());
        this.declareTopicService.createOrUpdateEntrustAdd(declareTopicVO);
        return ResponseVO.success();
    }
    @ControllerEndpoint(operation = "委托课题信息", exceptionMessage = "修改委托课题失败")
    @PostMapping("entrustUpdate")
    @ResponseBody
    public ResponseVO updateEntrust(@RequestBody DeclareTopicVO declareTopicVO) {
        this.declareTopicService.createOrUpdateEntrustAdd(declareTopicVO);
        return ResponseVO.success();
    }

    /**
     * 资格审查详情页面
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareEntrust/qualificationDetail/{declareId}")
    public String qualificationDetail(@PathVariable Long declareId, Model model){
        DeclareTopicVO declareTopicVO = declareTopicService.findByIdVo(declareId);
        model.addAttribute("result",declareTopicVO);
        return MyUtil.view("business/entrust/qualificationDetail");
    }



    /**
     * 信息审查
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareEntrust/check/{declareId}")
    public String check(@PathVariable Long declareId, Model model){
        //获取通知类型字典表
        model.addAttribute("declareId",declareId);
        return MyUtil.view("business/entrust/check");
    }


    @ControllerEndpoint(operation = "审查课题申报", exceptionMessage = "审查课题申报失败")
    @PostMapping("declareEntrust/checkInfo/commit")
    @ResponseBody
    @RequiresPermissions("declareEntrust:checkInfo")
    public ResponseVO checkDeclareTopic(DeclareTopic declareTopic) {
        DeclareEntrust declareEntrust=  declareEntrustService.findByDeclareId(declareTopic.getDeclareId());
        if(declareEntrust == null){
            throw new IllegalArgumentException("申请ID参数异常！");
        }
        if(!DictEnum.INFO_WAIT.getCode().equals(declareEntrust.getExamine())){
            return ResponseVO.failure("不是已待审核状态，无法审核！");
        }
        User currentUser = getCurrentUser();
        //查询编号
        DeclareTopic declare = declareTopicService.getById(declareTopic.getDeclareId());
        Topic topic = topicService.getById(declare.getTopicId());
        MaxIndex maxIndex = new MaxIndex();
        maxIndex.setType(declare.getLevelTypeCode());
        maxIndex.setYear(Integer.parseInt(topic.getYear()));

        declareEntrustService.updateCheckEntrust(declareTopic,currentUser,maxIndex);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "信息提交待审核", exceptionMessage = "信息提交审核失败")
    @PostMapping("infoApply/{entrustId}")
    @ResponseBody
    public ResponseVO infoApply(@PathVariable Long entrustId) {
        DeclareEntrust declareEntrust =new DeclareEntrust();
        declareEntrust.setEntrustId(entrustId);
        declareEntrust.setExamine(DictEnum.INFO_WAIT.getCode());
        declareEntrustService.updateDeclareEntrust(declareEntrust);
        //修改主表修改时间
        DeclareEntrust entrust = declareEntrustService.getById(entrustId);
        DeclareTopic declareTopic=new DeclareTopic();
        declareTopic.setDeclareId(entrust.getDeclareId());
        declareTopicService.updateById(declareTopic);

        return ResponseVO.success();
    }
    @ControllerEndpoint(operation = "变更信息提交待审核", exceptionMessage = "变更信息提交待审核")
    @PostMapping("changeApply")
    @ResponseBody
    public ResponseVO changeApply(@RequestBody DeclareTopicVO declareTopicVO) {
        this.declareTopicService.changeApplyDeclareTopicVO(declareTopicVO);
        //修改主表修改时间
        DeclareTopic declareTopic=new DeclareTopic();
        declareTopic.setDeclareId(declareTopicVO.getDeclareId());
        declareTopicService.updateById(declareTopic);
        return ResponseVO.success();
    }


    /**
     * 信息变更审查页面跳转
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareEntrust/checkChange/{declareId}")
    public String checkMember(@PathVariable Long declareId, Model model){
        //获取通知类型字典表
        //获取通知类型字典表
        DeclareTopic declareTopic = declareTopicService.getById(declareId); ;
        ApplicantInfo applicantInfo = applicantInfoService.getById(declareTopic.getApplicantId());
        DeclareEntrust declareEntrust=  declareEntrustService.findByDeclareId(declareId);

        model.addAttribute("declareId",declareId);
        model.addAttribute("appCompany",applicantInfo.getCompany());
        if(applicantInfo.getCompany().equals(declareEntrust.getChangeCompany())){
            model.addAttribute("updateCompany","");
        }else {
            model.addAttribute("updateCompany",declareEntrust.getChangeCompany());
        }
        return MyUtil.view("business/entrust/checkChange");
    }
    @ControllerEndpoint(operation = "信息变更审查", exceptionMessage = "信息变更审查失败")
    @PostMapping("declareEntrust/checkChange/commit")
    @ResponseBody
    @RequiresPermissions("declareEntrust:checkChange")
    public ResponseVO checkChange(DeclareTopic declareTopic) {
        DeclareEntrust declareEntrust=  declareEntrustService.findByDeclareId(declareTopic.getDeclareId());
        if(declareEntrust == null){
            throw new IllegalArgumentException("申请ID参数异常！");
        }
        if(!DictEnum.CHANGE_WAIT.getCode().equals(declareEntrust.getExamineChange())){
            return ResponseVO.failure("不是信息改变待审核状态，无法审核！");
        }
        User adminUser = getCurrentUser();
        declareEntrustService.updateCheckMember(declareTopic,adminUser);
        return ResponseVO.success();
    }

    /**
     * 延期审查
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/declareEntrust/checkDelay/{declareId}")
    public String checkDelay(@PathVariable Long declareId, Model model){
        //查询延期审核记录
        DelayApply delayApply=   delayApplyService.findDelayApplyByDeclareId(declareId);
        if(delayApply==null){
            delayApply=new DelayApply();
        }
        if(delayApply.getDelayFileId()!=null){
            //附件
            SysFile byId = sysFileService.getById(delayApply.getDelayFileId());
            delayApply.setDelayFileName(byId.getName());
        }
        model.addAttribute("declareId",declareId);
        model.addAttribute("delayApply",delayApply);
        return MyUtil.view("business/entrust/checkDelay");
    }
    @ControllerEndpoint(operation = "延期审查", exceptionMessage = "延期审查失败")
    @PostMapping("declareEntrust/checkDelay/commit")
    @ResponseBody
    @RequiresPermissions("declareEntrust:checkDelay")
    public ResponseVO checkDelay(DeclareTopic declareTopic) {
        DeclareEntrust declareEntrust=  declareEntrustService.findByDeclareId(declareTopic.getDeclareId());
        if(declareEntrust == null){
            throw new IllegalArgumentException("申请ID参数异常！");
        }
        if(!DictEnum.DELAY_WAIT.getCode().equals(declareEntrust.getExamineDelay())){
            return ResponseVO.failure("不是延期待审核状态，无法审查！");
        }
        User adminUser = getCurrentUser();
        declareEntrustService.updateCheckDelay(declareTopic,adminUser);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "延期提交待审核", exceptionMessage = "延期待审核失败")
    @PostMapping("delayEntrustApply")
    @ResponseBody
    public ResponseVO delayApply(DelayApply delayApply) {
        //插入
       declareEntrustService.applyDelayApply(delayApply);
        DeclareTopic declareTopic=new DeclareTopic();
        declareTopic.setDeclareId(delayApply.getDeclareId());
        declareTopicService.updateById(declareTopic);
        return ResponseVO.success();
    }

    @GetMapping("memberUpdate/list")
    @ResponseBody
    public ResponseVO indicatorList(QueryRequest request, MemberInfoRecord memberInfoRecord) {
        //所有组成员
        memberInfoRecord.setMemberType(1);
        PageInfo<MemberInfoRecord> pageInfo =  memberInfoRecordService.findMemberInfoRecords(request, memberInfoRecord);
        return ResponseVO.success(pageInfo);
    }

    /**
     * 结项申请
     * @return
     */
    @ControllerEndpoint(operation = "结项申请", exceptionMessage = "结项申请失败")
    @PostMapping("biz/declareEntrust/conclusion")
    @ResponseBody
    public ResponseVO conclusion(DeclarePlan declarePlan){

        DeclareEntrust entrust=  declareEntrustService.findByDeclareId(declarePlan.getDeclareId());
        if(!DictEnum.INFO_PASSED.getCode().equals(entrust.getExamine())){
            return ResponseVO.failure("课题审核未通过!");
        }

        if(DictEnum.DELAY_WAIT.getCode().equals(entrust.getExamineDelay())){

            return ResponseVO.failure("课题延期待审核中，管理员审核之后才可以结项！");
        }
        if(DictEnum.CHANGE_WAIT.getCode().equals(entrust.getExamineChange())){
            return ResponseVO.failure("课题变更待审核中，管理员审核之后才可以结项！");
        }
       //以上都满足可以申请结项鉴定
        User adminUser = getCurrentUser();
        declareTopicService.updateConclusion(declarePlan,adminUser.getUsername(),entrust.getEntrustId());

        return ResponseVO.success();
    }

}
